Javascript Array Join
方法中有多少个操作?
这只是一次操作,还是操作次数与数组中的项数相同?
我问的原因是因为我想知道比较以下两个数组的最便宜的方法是什么:
var a = ["Apples", "Pears", "Bananas"]
var b = ["Apples", "Oranges", "Bananas"]
方法A
For (var i = 0; i < 2; i++) {
if (a[i] === b[i]) console.log(false);
}
方法B
aa = a.join("&");
bb = b.join("&");
if (aa === bb) console.log(false)
最便宜的方法,无需只编写 a === b
,因为重点是比较两个不同数组中的值。
最佳答案
ECMAScript 2015 (6th Edition, ECMA-262) 的 Array.prototype.join(分隔符)
执行以下步骤:
Let O be ToObject(this value).
ReturnIfAbrupt(O).
Let len be ToLength(Get(O, "length")).
ReturnIfAbrupt(len).
If separator is undefined, let separator be the single-element String ",".
Let sep be ToString(separator).
ReturnIfAbrupt(sep).
If len is zero, return the empty String.
Let element0 be Get(O, "0").
If element0 is undefined or null, let R be the empty String; otherwise, let R be ToString(element0).
ReturnIfAbrupt(R).
Let k be 1.
Repeat, while k < len
Let S be the String value produced by concatenating R and sep.
Let element be Get(O, ToString(k)).
If element is undefined or null, let next be the empty String; otherwise, let next be ToString(element).
ReturnIfAbrupt(next).
Let R be a String value produced by concatenating S and next.
Increase k by 1.
Return R.
注释:
- 数组的元素被转换为字符串,然后将这些字符串连接起来,并通过出现的分隔符进行分隔。如果未提供分隔符,则使用单个逗号作为分隔符。
- join 函数有意是通用的;它不要求其 this 值是一个 Array 对象。因此,它可以转移到其他类型的对象中作为方法使用。
我想说你的第一种方法更便宜:)但是你可以运行你自己的基准测试。
关于javascript - Javascript 数组连接操作中有多少个操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33461703/