From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../global_objects/array/unshift/index.html | 120 +++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 files/zh-cn/web/javascript/reference/global_objects/array/unshift/index.html (limited to 'files/zh-cn/web/javascript/reference/global_objects/array/unshift/index.html') diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/unshift/index.html b/files/zh-cn/web/javascript/reference/global_objects/array/unshift/index.html new file mode 100644 index 0000000000..7b1148813f --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/array/unshift/index.html @@ -0,0 +1,120 @@ +--- +title: Array.prototype.unshift() +slug: Web/JavaScript/Reference/Global_Objects/Array/unshift +tags: + - Array + - JavaScript + - Method + - 原型 + - 参考资料 + - 数组 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift +--- +

{{JSRef}}

+ +

unshift() 方法将一个或多个元素添加到数组的开头,并返回该数组的新长度(该方法修改原有数组)

+ +
{{EmbedInteractiveExample("pages/js/array-unshift.html")}}
+ +

语法

+ +
arr.unshift(element1, ..., elementN)
+
+ +

参数列表

+ +
+
elementN
+
要添加到数组开头的元素或多个元素。
+
+ +

返回值

+ +

当一个对象调用该方法时,返回其 {{jsxref("Array.length", "length")}} 属性值。

+ +
+
+ +

描述

+ +

unshift 方法会在调用它的类数组对象的开始位置插入给定的参数。

+ +

unshift 特意被设计成具有通用性;这个方法能够通过 {{jsxref("Function.call", "call")}} 或 {{jsxref("Function.apply", "apply")}} 方法作用于类数组对象上。不过对于没有 length 属性(代表从0开始的一系列连续的数字属性的最后一个)的对象,调用该方法可能没有任何意义。

+ +

注意, 如果传入多个参数,它们会被以块的形式插入到对象的开始位置,它们的顺序和被作为参数传入时的顺序一致。 于是,传入多个参数调用一次 unshift ,和传入一个参数调用多次 unshift (例如,循环调用),它们将得到不同的结果。例如:

+ +
let arr = [4,5,6];
+arr.unshift(1,2,3);
+console.log(arr); // [1, 2, 3, 4, 5, 6]
+
+arr = [4,5,6]; // 重置数组
+arr.unshift(1);
+arr.unshift(2);
+arr.unshift(3);
+console.log(arr); // [3, 2, 1, 4, 5, 6]
+
+ +

示例

+ +
let arr = [1, 2];
+
+arr.unshift(0); // result of the call is 3, which is the new array length
+// arr is [0, 1, 2]
+
+arr.unshift(-2, -1); // the new array length is 5
+// arr is [-2, -1, 0, 1, 2]
+
+arr.unshift([-4, -3]); // the new array length is 6
+// arr is [[-4, -3], -2, -1, 0, 1, 2]
+
+arr.unshift([-7, -6], [-5]); // the new array length is 8
+// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.13', 'Array.prototype.unshift')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ESDraft')}}
+ +

浏览器兼容性

+ + + +

{{Compat("javascript.builtins.Array.unshift")}}

+ +

参见

+ + -- cgit v1.2.3-54-g00ecf