Вопрос

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.

jsFiddle

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);
Это было полезно?

Решение 2

You can use Array.indexOf jsfiddle

var obj = {arr: [{x: 1, y: 2},{x: 3, y: 4},{x: 5, y: 6}]};

function myFunction(myObj)
{
    alert(obj.arr.indexOf(myObj)); 
}

myFunction(obj.arr[2]);

Другие советы

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. 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.

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.

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 с атрибуция
Не связан с StackOverflow
scroll top