必须单独回答,以确保清楚。查看数组中是否包含某些东西的正确方法:
var myArr = ['apples', 'bananas', 'pears'];
if (myArr.indexOf('pears') > -1) { // myArr.indexOf('pears') will equal the number 2
console.log('we got pears'); // this will log
}
if (myArr.indexOf('hotdogs') > -1) { // since it's not in the array, it's -1
console.log('hotdog!'); // this will not log
}
最后请注意,for...in
实际上不应使用循环来遍历数组-确实存在用于遍历对象中的键的循环。为了遍历JS中的数组,经典的for
循环是正确的方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句