[英]JavaScript Extended Array doesn't work as expected with no error message
您好,我正在為我的項目學習JavaScript。 我對此簡短代碼有疑問。
function randomArr(){};
randomArr.prototype = new Array();
randomArr.prototype.getRandomValue = function(){
var index = Math.floor(this.length * Math.random()); // return 0~1
return this[index];
}
var arr = new randomArr('seoul', 'tokyo', 'beijing');
console.log(arr.getRandomValue());
當我在Web瀏覽器中運行此代碼時,輸出只是未定義的。
對我來說,最好將該函數添加到Array類型中:
Array.prototype.getRandomValue = function(){
var index = Math.floor(this.length * Math.random()); // return 0~1
return this[index];
}
Array arr = new Array('seoul', 'tokyo', 'beijing');
console.log(arr.getRandomValue());
看看這個有趣的解釋: https : //coderwall.com/p/h4xm0w/why-never-use-new-array-in-javascript
根據該鏈接,您應該使用數組,如下所示:
var arr = ['seoul', 'tokyo', 'beijing'];
console.log(arr.getRandomValue());
希望這可以幫助!
ES6類的一大好處是它們可以對“異類”類進行子類化,例如數組。 可以將舊版本的Javascript欺騙到子類化數組中,但是不值得在這里進行解釋。
另一個問題是,您使用的ES6之前版本Javascript的子類繼承模式非常差,可以實例化基類並將基類的實例添加到新類的原型鏈中,而不是先將它們粘在一起。 這是Typescript在后台執行的操作,但是做出了一些可怕的假設。 在您的情況下,在提供城市列表之前,Array構造函數已經被調用很長時間,並且創建了一個空數組,因此即使您可以對此類進行子類化,也會失敗。
此代碼是執行此操作的現代方法。 我采取了額外的步驟來解決Eleazar鏈接中提出的問題,方法是不直接將構造函數的參數傳遞給Array基本構造函數,而是讓基本構造函數創建一個空數組,然后將值推入其中。
class randomArr extends Array{
constructor(..._items){
super()
_items.forEach(_=>this.push(_))
}
getRandomValue(){
const index=Math.floor(this.length*Math.random())
return this[index]
}
}
let arr=new randomArr('seoul', 'tokyo', 'beijing')
console.log(arr.getRandomValue())
盡管有Eleazer的建議,但我還是避免添加具有命名屬性的核心原型。 我發現Symbol屬性非常適合此目的。 如下所示:
const getRandomValue=Symbol()
Reflect.defineProperty(
Array.prototype,
getRandomValue,
{
value(){
const index=Math.floor(this.length*Math.random())
return this[index]
}
}
)
let arr=['seoul', 'tokyo', 'beijing']
console.log(arr[getRandomValue]())
符號路由的優點是可以確保您不會與另一個擴展Array原型的庫發生名稱沖突。
這是使用原型鏈並避免將方法直接添加到Array.prototype的方法。
function randomArr() {
Array.call(this);
for (x in arguments) {
this.push(arguments[x]);
}
}
randomArr.prototype = Object.create(Array.prototype);
randomArr.prototype.constructor = randomArr;
randomArr.prototype.getRandomValue = function(){
var index = Math.floor(this.length * Math.random()); // return 0~1
return this[index];
}
var arr = new randomArr('seoul', 'tokyo', 'beijing');
alert(arr.splice(1,1)); // works as desired
alert(arr.getRandomValue()); // works fine
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.