JavaScript not returning int ..at least not when I think it should be
Assuming that arr
is an array of objects.
arr开发者_运维问答 = // some items;
function findItem( source, item ) {
return source.indexOf(item);
}
Now, I know the code is correct, it actually does find the right index, but I get an 'undefined
' response. However if I do this..
function findItem( source, item ) {
var i = 0;
i = source.indexOf(item);
return i;
}
I get the right index.
I've even tried.
function findItem(source, item) {
return parseInt( source.indexOf(item) );
}
and I still get an 'undefined
'.
Can someone tell me what in the world is going on?
Okay, to make things a bit simpler, I'll post more code here.
function init() {
alert(discoverWithoutVar());
alert(discoverWithVar());
}
function discoverWithoutVar() {
var arr = [{ Name: "Stacey" }, { Name: "Ciel" }, { Name: "Derek" }, { Name: "Christi"}];
// find the index of 'Ciel'
arrayForEach(arr, function (e) {
if (e.Name == "Ciel") {
return arrayIndexOf(arr, e);
}
});
}
function discoverWithVar() {
var arr = [{ Name: "Stacey" }, { Name: "Ciel" }, { Name: "Derek" }, { Name: "Christi"}];
var i = 0;
// find the index of 'Ciel'
arrayForEach(arr, function (e) {
if (e.Name == "Ciel") {
i = arrayIndexOf(arr, e);
}
});
return i;
}
function arrayForEach(array, action) {
for (var i = 0, j = array.length; i < j; i++)
action(array[i]);
}
function arrayIndexOf(array, item) {
if (typeof array.indexOf == "function")
return array.indexOf(item);
for (var i = 0, j = array.length; i < j; i++)
if (array[i] == item)
return i;
return -1;
}
Just to prove I wasn't lying about it working, a screenshot of the debugger. I would advise you take a very close look at what you are passing for your variables.
Like Matthew said, you discard the value. Adding a return on arrayForEach would return the value found by your functions.
This is why you should post real code you've tested with. If you want to simplify, make it is as simple as you can while still showing the problem. Then post that.
function discoverWithoutVar() {
var arr = [{ Name: "Stacey" }, { Name: "Ciel" }, { Name: "Derek" }, { Name: "Christi"}];
// find the index of 'Ciel'
arrayForEach(arr, function (e) {
if (e.Name == "Ciel") {
return arrayIndexOf(arr, e);
}
});
}
is wrong, because you're just returning from the anonymous function you pass to the for each (not from discoverWithoutVar
).
function arrayForEach(array, action) {
for (var i = 0, j = array.length; i < j; i++)
action(array[i]); // The value you return is being discarded here
}
Just use a regular for loop:
for(var i = 0; i < arr.length; i++)
{
if (arr[i].Name == "Ciel") {
return arrayIndexOf(arr, e);
}
}
The reason the var i
makes it work is that i
is being closed into the anonymous function. Then, you're setting it inside, but returning from the outer function. If the var i
, i =
, and return were all in the anonymous function, it would indeed make no difference.
精彩评论