在您的特定情况下,您可以使用一个无聊的旧柜台来做到这一点:
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(key,10))检查的幼稚的循环。
离题 :
另一种写法
var windowArray = new Array ("item","thing","id-3-text","class");是
var windowArray = ["item","thing","id-3-text","class"];
…这对您来说键入的次数较少,也许(这一点是主观的)更容易阅读。这两个语句的结果完全相同:具有这些内容的新数组。



