小码哥的IT人生

JavaScript Array prototype 属性

JavaScript基础 2022-05-13 16:29:31小码哥的IT人生shichen

JavaScript Array prototype 属性

实例

创建一个新的数组方法,将数组值转换为大写:

Array.prototype.myUcase = function() {
  for (i = 0; i < this.length; i++) {
    this[i] = this[i].toUpperCase();
  }
};

创建一个数组,然后调用 myUcase 方法:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.myUcase();

完整实例:

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript 数组</h1>
<p>prototype 构造函数允许您向 Array() 对象添加新的属性或方法。</p>
<p id="demo"></p>
<script>
// 添加新方法
Array.prototype.myUcase = function() {
  for (let i = 0; i < this.length; i++) {
    this[i] = this[i].toUpperCase();
  }
};
// 在任何数组上使用该方法
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.myUcase();
document.getElementById("demo").innerHTML = fruits;
</script>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

定义和用法

prototype 是可用于所有 JavaScript 对象的全局构造函数。

prototype 引用全局 Array() 对象。

prototype 构造函数允许您向数组添加新的属性和方法。

当构造新属性时,所有数组都将获得此属性及其值。

当构造新方法时,所有数组都将获得此方法。

浏览器支持

所有浏览器都完全支持 prototype:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Yes Yes Yes Yes Yes Yes

语法

Array.prototype.name = value

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024