创建一个函数,该函数接受一个对象和一个键作为输入-返回对象中键的值

Create a function that takes an object and a key as input - return value for key within the object

本文关键字:函数 一个 输入 返回 对象 一个对象 创建      更新时间:2023-09-26

刚刚学习JS,在coursera上遇到这个问题。我甚至无法开始回答这个问题;我不确定它在问什么。很抱歉我的无知。只是在寻找基本的格式。我可以写一个接受输入的函数,但不确定怎么做。我花了一段时间研究对象,但还没有完全理解。谢谢!

需要使用多个参数。您需要用逗号分隔参数,如:

function func(param1, param2) {
    console.log("Parameter 1: " + param1);
    console.log("Parameter 2: " + param2);
}
func(1, 2);
// Console:
// Parameter 1: 1
// Parameter 2: 2

在实际代码中看起来像这样:

function getValue(object, key) {
    if (object.hasOwnProperty(key)) {
        // Object.prototype.hasOwnProperty(key) returns if the specified object has the specified key in it 
        return object[key];
    } else {
        // The else statement is not really needed as the function already returned
        // if the object has the specified key
        return null;
        // If you need this function for something specific, then you should return a default value
    }
}

clear and clear:

function f(obj,keyname){
    return obj[keyname];
}

用法:f(myObj,my_key_field_name)

或者简单的obj[keyname]如果你不喜欢写一个函数