如何检查对象中是否存在属性?

时间:2016-11-27 21:28:36

标签: javascript node.js

道歉。我很确定这是一个相当新手的问题;但是,它来了!感谢您提前提示:)

我的应用程序中有以下功能,现在运行应用程序会抛出错误“TypeError:parameters.includes不是函数”。这个错误是什么意思? if语句是否需要函数?我应该如何设置这个条件?

function handleApiAiAction(sender, action, responseText, contexts, parameters, response) {
    switch (action) {
        case "job-search":
            console.log(parameters);
            if (parameters.includes("quickreply")) {
                console.log("it worked");
            } else {
                let replies = response.result.fulfillment.messages[0].replies;
                let title = response.result.fulfillment.messages[0].title;
                sendQuickReply(sender, title, replies);
                console.log("it didn't work");
            }
            break;
        default:
            //unhandled action, just send back the text
            sendTextMessage(sender, responseText);
    }
}

console.log('parameters')给了我:

{ quickreply: 'quickreply' }

[some edits:)]

2 个答案:

答案 0 :(得分:3)

class User < ApplicationRecord enum status: [:new, :editor, :admin, :blocked] end 不是对象的有效方法。您可以使用:

includes

答案 1 :(得分:1)

{ quickreply: 'quickreply' }不包含对象成员includes: function() {}Object.prototype也不包含)。

您尝试做的事情是检查对象是否包含属性quickreply,因此您应该执行以下操作:

if('quickreply' in parameters) {
  // do stuff
}

您还可以使用其他方法,例如hasOwnProperty。他们每个人都有自己的细微差别,但in看起来应该适合你的情况。