简体   繁体   English

返回从最终 object 推入对象数组的键

[英]Return key from final object pushed into an array of objects

Trying to return the last key from an object pushed into an array试图从推入数组的 object 返回最后一个键

var remove = function(s, k) {
   let stack = [];
   let newObj = {}; 
   for(const char of s){
    let letter = stack[stack.length-1]
    console.log(`stack: ${stack[stack.length-1][0]}`)
    if(char !== letter){
        newObj[char] = newObj[char] ? newObj[char]+1 : 1
[Object.values(newObj).length-1])
        stack.push({newObj})
    } 
    else if(char === letter && Object.values(newObj)[Object.values(newObj).length-1]){
        stack.pop()
    }
    }
}

If I pass in如果我通过

const s = "deeedbbcccbdaa"; 
const k = 3;

I expect my console.logs to retun the last letter I pushed into the array.我希望我的 console.logs 重新调整我推入数组的最后一个字母。 However this is what I'm seeing currently:然而,这是我目前看到的:

TypeError: Cannot read properties of undefined (reading '0')

Can't we use unshift我们不能使用unshift

let text = "deeedbbcccbdaa";
const myArray = text.split("");

console.log(myArray[myArray.unshift()-1])

Try it试试看

You are getting this error because the before you enter the for loop, you assign stack to an empty array ( let stack = [] ).您收到此错误是因为在进入for循环之前,您将stack分配给一个空数组( let stack = [] )。

This means that on the first iteration of your for loop, you are trying to access the last element of stack in your console.log statement, even though it doesn't exist yet.这意味着在您的for循环的第一次迭代中,您试图访问console.log语句中堆栈的最后一个元素,即使它还不存在。

In other words, the first time your for loop runs, stack[stack.length-1] is undefined.换句话说,你的for循环第一次运行时, stack[stack.length-1]是未定义的。 So the error comes from trying to access index 0 of this value.所以错误来自试图访问这个值的索引 0。

Hope that helps!希望有帮助!

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

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