一个Javascript数组联接操作中有多少个操作

How many operations are there in a Javascript Array Join operation?

本文关键字:操作 多少 Javascript 数组 一个      更新时间:2023-09-26

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(第6版,ECMA-262)的Array.prototype.join (separator)执行以下步骤:

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.

注:

  • 数组的元素被转换为字符串,然后这些字符串被连接起来,用分隔符分隔。如果没有提供分隔符,则使用单个逗号作为分隔符
  • 联接函数是有意通用的;它不要求其this值是Array对象。因此,它可以被转移到其他类型的对象中用作方法

我想说你的第一种方法更便宜:)但你可以运行自己的基准测试。

几乎根据定义,没有什么比下面更快的了,假设你想做一个肤浅的比较。

function equal(a, b) {
  if (a === b) return true;
  if (a.length !== b.length) return false;
  for (var i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
  return true;
}

快速测试表明,这比使用joinstringify快50倍。