为了提高效率,您可以存储每个项目的位置,然后使用它来引用名称:
var things = [
{
id: "12345",
name: "Bryan"
},
{
id: "55555",
name: "Justin"
}
], reference = things.map(function(a){ return a.id });;
function replace (id, name, ar, ref) { ref.indexOf(id)>-1&&(ar[ref.indexOf(id)]['name']=name); }
replace("55555", "Phil", things, reference);
在这种情况下,您只需要循环一次。然后所有信息都存储在reference 变量中。 reference 存储id 所在的位置,我们使用它来避免循环。我不确定编译器在做什么以及它是否循环,但这只是感觉更有效率。
.indexOf 不完全受支持,因此您可以使用 PollyFill
将此代码添加到 JavaScript 文件的顶部:
[].indexOf||(Array.prototype.indexOf=function(a,b,c){for(c=this.length,b=(c+~~b)%c;b<c&&(!(b in this)||this[b]!==a);b++);return b^c?b:-1;})
和
Array.prototype.map||(Array.prototype.map=function(r,t){var n,o,e;if(null==this)throw new TypeError(" this is null or not defined");var i=Object(this),a=i.length>>>0;if("function"!=typeof r)throw new TypeError(r+" is not a function");for(arguments.length>1&&(n=t),o=new Array(a),e=0;a>e;){var p,f;e in i&&(p=i[e],f=r.call(n,p,e,i),o[e]=f),e++}return o});
还有:
Array.prototype.forEach||(Array.prototype.forEach=function(r,t){var o,n;if(null==this)throw new TypeError(" this is null or not defined");var e=Object(this),i=e.length>>>0;if("function"!=typeof r)throw new TypeError(r+" is not a function");for(arguments.length>1&&(o=t),n=0;i>n;){var a;n in e&&(a=e[n],r.call(o,a,n,e)),n++}});
检索自:here、here 和 here
注意:虽然 IE 8 及更低版本不支持indexOf,但几乎所有其他浏览器都支持。