简体   繁体   English

Javascript:函数和数组作为键/值对

[英]Javascript: Functions and arrays as key/value pairs

1) In some other languages define function as parameterized block of statements, and on syntactic level javascript function also looks like this, until it's said that it can have it's own properties and methods.How can it be syntactically represented as key/value pair? 1)在其他一些语言中,将函数定义为参数化的语句块,在语法层面上,javascript函数也是这样的,直到据说它可以拥有自己的属性和方法。如何在语法上表示为键/值对? And where does function code live?函数代码在哪里?

 var x = function(a,b){alert('Hi');};
    // x = { _code: "alert('Hi'), _arguments: {a:.., b:..,}}

here code and arguments are my imaginary internal properties这里的代码和参数是我想象的内部属性

2) If array is key/value pair, can i think that array indexes are just object keys? 2)如果数组是键/值对,我可以认为数组索引只是对象键吗?

var a = ["elem1", "elem2"];
// a = {0: "elem1", 1: "elem2"}

Expanding on my comment that EVERYTHING in JavaScript is a object.扩展我的评论,即 JavaScript 中的一切都是一个对象。

var arr = [

  function () {

    console.log("Well... Look at that.");

  }

];


var obj = arr[0];

obj();

var newObj = Object.assign({}, arr);

console.log(newObj);

newObj[0]();

How can it be syntactically represented as key/value pair?它如何在语法上表示为键/值对?

It can't.它不能。

The executable code of a function is not expressed in terms of properties on an object.函数的可执行代码不是根据对象的属性来表达的。

And where does function code live?函数代码在哪里?

That's an implementation detail of the JavaScript engine, not something that is exposed to JavaScript code in a standard way.这是 JavaScript 引擎的实现细节,而不是以标准方式向 JavaScript 代码公开的内容。

If array is key/value pair, can i think that array indexes are just object keys?如果数组是键/值对,我可以认为数组索引只是对象键吗?

They are just properties.他们只是性能。 See the specification :规格

Array objects give special treatment to a certain class of property names.数组对象对特定类别的属性名称给予特殊处理。 A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2 32 −1.当且仅当 ToString(ToUint32(P)) 等于 P 且 ToUint32(P) 不等于 2 32 -1 时,属性名称 P(以字符串值的形式)是数组索引。 A property whose property name is an array index is also called an element.属性名称为数组索引的属性也称为元素。 Every Array object has a length property whose value is always a nonnegative integer less than 2 32 .每个 Array 对象都有一个 length 属性,其值始终是一个小于 2 32的非负整数。 The value of the length property is numerically greater than the name of every property whose name is an array index; length 属性的值在数字上大于名称为数组索引的每个属性的名称;

… and so on. … 等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM