How does js find the subscript where name is' Xiaohong'?

the data goes like this:

var obj = [
    {
        id:1,
        name:""
    },
    {
        id:2,
        name:""
    },
    {
        id:3,
        name:""
    }
];

now I want to know what the subscript for "Xiao Hong" is for name

//,
function findIndex(arr,key,word){
    arr.map((o,n)=>{
        if(o[key] == word){
            return n;
        }
    })
}
var t = findIndex(obj,"name","");
console.log(t); //underfine
Jul.11,2022
The
const findIndex = (arr, key, word) => arr.findIndex(obj => obj[key] === word);

function does not return a value, so it is undefined.


The return in

map is returned to the map array. In the question, arr.map is assigned [undedined,1,undefined] when he finishes running. So your findindex returns a null value. You can add a return before arr.map to see the return value.
can be changed to this, and that's fine.

function findIndex(arr,key,word){
    arr.map((o,n)=>{
        if(o[key] == word){
            console.log(n);
        }
    });
}

clipboard.png


function findIndex(arr,key,word){
  return arr.find(item => {
    return item.name === word
  })
}
var t = findIndex(obj,'name','');
console.log(t); //{id: 2, name: ""}

  

your findIndex has no return value, brother dei
you define a variable outside the map function, and
assign a value in the map.
Last return outside the map function

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e48a0c-4420f.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e48a0c-4420f.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?