下面应该警告“true”,但是,它警告“No item”。我在这个代码上出错了。有什么线索吗?
Array.prototype.CheckColor = function (datain) {
for (var i = 0, len = this.length; i < len; i++) {
if (this[i] === datain) {
return true;
} else {
return "No item";
}
}
}
var newstr = "red blue green".split(" ");
var oyrsval = Array.prototype.CheckColor.call(newstr, "blue");
alert(oyrsval);
最佳答案
应该是
Array.prototype.CheckColor = function(datain){
for (var i = 0, len = this.length; i < len;i++ ){
if (this[i] === datain){
return true; // Return true if found
}
}
return "No item"; // else return
}
或者使用 indexOf 更简单:
Array.prototype.CheckColor = function(datain){
return this.indexOf(datain) > -1 ? true : "No item";
}
关于javascript - 调用方法在 JavaScript 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27820352/