更新时间:2023-02-22 12:08:02
在特定的情况下,你可以只是一个无聊的老计数器做到这一点:
In your specific case, you can do it just with a boring old counter:
var index, value, result;
for (index = 0; index < windowArray.length; ++index) {
value = windowArray[index];
if (value.substring(0, 3) === "id-") {
// You've found it, the full text is in `value`.
// So you might grab it and break the loop, although
// really what you do having found it depends on
// what you need.
result = value;
break;
}
}
// Use `result` here, it will be `undefined` if not found
但如果你的数组是的稀疏的,你可以做到这一点更有效地与正确设计的的for..in
循环:
var key, value, result;
for (key in windowArray) {
if (windowArray.hasOwnProperty(key) && !isNaN(parseInt(key, 10))) {
value = windowArray[key];
if (value.substring(0, 3) === "id-") {
// You've found it, the full text is in `value`.
// So you might grab it and break the loop, although
// really what you do having found it depends on
// what you need.
result = value;
break;
}
}
}
// Use `result` here, it will be `undefined` if not found
谨防没有那么幼稚的for..in
环路的hasOwnProperty
和 !isNaN(parseInt函数(键,10))
检查; 这里的原因。
题外话
另一种方式来写
var windowArray = new Array ("item","thing","id-3-text","class");
是
var windowArray = ["item","thing","id-3-text","class"];
...这是你少打字,也许(这一点是主观的)多一点轻松阅读。这两个语句具有完全相同的结果:与内容的新数组
...which is less typing for you, and perhaps (this bit is subjective) a bit more easily read. The two statements have exactly the same result: A new array with those contents.