如何在javascript中创建静态数组 [英] How to create static array in javascript

查看:177
本文介绍了如何在javascript中创建静态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个静态数组。但我发现它可以在运行时增加数组中的项。我如何在javascript中实现静态数组?为什么数组在javascript中是可变的?

  var a = []; 
// var a = new Array(3);
for(var i = 0; i< 5; i ++){
//a.push(i);
a [i] = i;
}

document.write(a);

Object.freeze



 use strict; var a = Object.freeze([0 ,1,2]); console.log(a);试试{a.push(3); //错误} catch(e){console.error(e);} try {a [0] =zero; //错误} catch(e){console.error(e);} console.log(a);  



不允许




  • 更改现有属性,无论是值还是其他功能,如是否'可扩展等等。

  • 添加或删除属性



有关详细信息,请参阅链接。如果只是想要保持大小固定但是想要允许更改条目的值,只需使用 Object.seal



请注意,尝试更改现有属性是否会导致错误(与静默失败相反)取决于您是否处于严格模式。



冻结和封条,因此应该在任何含糊不清的情况下出现 - 日期浏览器。过时的浏览器不会有它们。


I am trying to create a static array. But I found that it can increase the item in the array at run time. How I can achieve static array in javascript? Why array is mutable in javascript ?

 var a = [];
//var a = new Array(3);
 for (var i = 0; i < 5; i++) {
     //a.push(i);
       a[i] = i;
}

document.write(a);

jsfiddle

解决方案

You can freeze the array with Object.freeze:

"use strict";
var a = Object.freeze([0, 1, 2]);
console.log(a);
try {
  a.push(3);     // Error
} catch (e) {
  console.error(e);
}
try {
  a[0] = "zero"; // Error
} catch (e) {
  console.error(e);
}
console.log(a);

That disallows

  • Changing existing properties, either their values or their other features like whether they're extensible, etc.
  • Adding or removing properties

See the link for full details. If you just want to keep the size fixed but do want to allow changes to the values of entries, just use Object.seal instead.

Note that whether attempts to change existing properties result in an error (as opposed to silent failure) depends on whether you're in strict mode.

freeze and seal were introduced in ES5 (June 2009), and so should be present in any vaguely up-to-date browser. Obsolete browsers will not have them.

这篇关于如何在javascript中创建静态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆