首页 > 解决方案 > 如何从数组JS调用函数?

问题描述

我练习 JS 并尝试通过从数组调用函数来执行示例代码,但它返回未定义的函数输出。我无法理解它是如何工作的,因为我已经调用了具有函数的数组的索引,但是当我期望 1 时它显示两个输出。

const arr = [
    "test1",
    "test2",
    function(){console.log("hi")}
];

console.log(arr[2]());

输出:

Babel Compiler v6.4.4
Copyright (c) 2014-2015 Sebastian McKenzie
   
hi
undefined
=> undefined

标签: javascriptarrays

解决方案


console.log调用函数时意味着您正在打印函数的返回值。

只需通过添加应该解释的返回值来尝试以下操作。

const arr = [
    "test1",
    "test2",
    function(){console.log("hi")},
    function(){console.log("hello"); return "world"}
];

console.log('1. function return value here: ', arr[2]());
console.log('2. function return value here: ', arr[3]());


推荐阅读