你好,
我有這個代碼:
obj = {"ignoredid":"3329"},{"ignoredid":"19693"};
hit = "3329";
if (Object.values(obj).indexOf(hit) > -1) {
console.log('has it');
} else {console.log('doesnt');}
但我收到一條警告說: expected an identifier and instead saw an expression
這是為什么?這是小提琴
https://jsfiddle.net/o7u5L90h/1/
盡管有警告,但代碼在小提琴上運行良好,但在我的實際專案中卻沒有(無論如何它總是輸出“doesnt”)所以我想知道一旦我擺脫了警告它是否會起作用。我在這里缺少什么?
謝謝你。
uj5u.com熱心網友回復:
也許你想要物件陣列?然后你可以做這樣的事情
// Helper function to check array of objects
const hasIt = (obj, val) => {
for(const v of obj) if(v['ignoredid'] === val) return true;
return false;
}
// Define array of objects
const obj = [{"ignoredid":"3329"},{"ignoredid":"19693"}];
// Test it
if(hasIt(obj, "3329")) console.log('has it');
else console.log('doesnt');
或者用最近的方法
// Define array of objects
const obj = [{"ignoredid":"3329"},{"ignoredid":"19693"}];
// Test it
if(obj.find(o => o.ignoredid === '3329')) console.log('has it');
else console.log('doesnt');
uj5u.com熱心網友回復:
要回答您的真正問題,發生的事情是該陳述句obj = {ignoredid : 3329},{ignoredid : 19693};不會導致語法錯誤,但不會執行您期望的操作。
雖然不清楚你期望發生什么??。這就是為什么 lint 警告說expected an identifier and instead saw an expression
它被解釋為接近以下內容:
obj = {ignoredid : 3329}, {ignoredid : 19693};
console.log(JSON.stringify(obj));
// Is interpreted as
obj = {ignoredid : 3329}
{ignoredid : 19693}
console.log(JSON.stringify(obj));
// Or
((obj = {ignoredid : 3329}), {ignoredid : 19693});
console.log(JSON.stringify(obj))
在這兩種情況下,文字{ignoredid : 19693}都被丟棄并且不被程式使用。
請注意,如果您開始撰寫使用const/let甚至 var 的代碼,則不會遇到此問題,并且會被告知您有真正的語法錯誤,并且不會出現這種奇怪的行為。那是因為 aVariableDeclaration不是 an Expression,并且用逗號分隔的運算式是這里發生的事情。有關更多詳細資訊,請參閱答案的末尾。
未捕獲的語法錯誤:無效的解構賦值
const obj = {ignoredid : 3329}, {ignoredid : 19693};
console.log(JSON.stringify(obj));
解釋當前的行為
如果您打算將其作為obj = {ignoredid : 3329, ignoredid : 19693};,則意味著obj將是{ignoredid : 19693},即具有相同名稱的最后一個屬性勝出。
這就是為什么你總是得到console.log('doesnt'),你的物件不包含3329only的值19693;
解決方案
正如建議TARK,Umitigate和我,你應該使用陣列。我只是想回答真正的問題,因為即使在你古怪的宣告之外,這種行為也有點奇怪??
Gorier 技術細節解釋錯誤資訊
If you analyze the syntax tree of your example, you'll notice that the body of the program is an ExpressionStatement but it does not contain an assignment directly, instead, it contains a nested SequenceExpression which contains a separate AssignmentExpression and an ObjectExpression which is not what you intended
However, if you analyze the syntax tree of obj = {"ignoredid":"3329"};, you'll notice that there's an AssignmentExpression nested directly in the first ExpressionStatement of the program
So the message is indicating that it expected an Assignment but instead saw an Expression
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/347885.html
標籤:javascript 目的
上一篇:創建給定字符中指定型別的物件
