[英]index of array that is passed
How do I retrieve the index of the array that is passed? 如何检索所传递数组的索引? The solution I currently use is sending the index too, but that doesn't feel right.
我当前使用的解决方案也是发送索引,但是感觉不对。
var obj = {arr: [{x: 1, y: 2},{x: 3, y: 4},{x: 5, y: 6}]};
function myFunction(myObj)
{
alert(myObj); // 5
// alert(the index of the array that is passed); // 2
}
myFunction(obj.arr[2].x);
There's no real way to do what you're asking. 没有真正的方法可以完成您要问的事情。 JavaScript is purely call-by-value, which means that before a function call is made the arguments are completely evaluated.
JavaScript纯粹是按值调用,这意味着在进行函数调用之前,必须对参数进行完全评估。 All that's left after the evaluation is the final value, and a copy of that is passed to the function.
求值后剩下的就是最终值,并将其副本传递给函数。
You can of course write code that searches for a value in some relatively-global array, but that would be a waste of CPU cycles if you can instead simply pass the array index to the function. 当然,您可以编写代码以在某些相对全局的数组中搜索值,但是如果您可以简单地将数组索引传递给函数,则将浪费CPU周期。
You can't do that, because the array or the index is not passed to the function, or even the object. 您不能这样做,因为数组或索引没有传递给函数,甚至没有传递给对象。
The array is read from the arr
property of the object, then an object is read from the array, then the value is read from the x
property of that object, and the function is called with that value. 从对象的
arr
属性读取数组,然后从数组读取对象,然后从对象的x
属性读取值,并使用该值调用函数。
Once inside the function, you can't tell that the value came from a property of an object, or that the object was stored in an array, or that the array was in turn a property in an object. 一旦进入函数,您就无法分辨出该值来自对象的属性,还是该对象存储在数组中,或者该数组又是对象中的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.