【发布时间】:2017-05-31 20:32:20
【问题描述】:
我在使用 fetch 理解变量和函数时遇到了一些问题。 我正在尝试从
传递响应的值.then(response => response.json())
到
.then(lang => response['lang'].slice(-2)
但是我得到了未定义的变量响应错误,所以我没有正确引用变量。正确的称呼方式是什么?
我还想调用两个控制台日志,下面的代码目前可以这样做,但我认为我不应该覆盖响应函数,我可以自己调用不带参数的函数或命令吗?
.then(response => console.log(response['text']) & console.log(food))
console.log(response['text']) & console.log(food)
fetch("https://localhost:8000", {method:"POST", body:fd})
.then(response => response.json())
.then(lang => response['lang'].slice(-2))
.then(food => "Temporary")
.then(function detectType(lang) {
switch(lang) {
case 'abc':
food = "Bananas";
break;
case 'def':
food = "Apples";
break;
default:
food = "Bananas";
break;
}})
.then(response => console.log(response['text']) & console.log(food))
.catch(err => console.error(err));
}
【问题讨论】:
-
为什么把函数的参数命名为
lang?你没有用它做任何事情。它应该是.then(response => response['lang'].slice(-2))(但不管你叫什么参数)。参数只能在定义它们的函数中访问。另见What is the scope of variables in JavaScript? -
如果我对参数这样做,那么当我尝试调用 response['text'] 时会发生什么?这是一个 json 字典,类型为 {'text':'a', 'lang':'b'}
-
如果“调用”只是指“访问”,它将返回字符串
'a'。示例:var foo = {text: 'a'}; console.log(foo['text']);. -
不,我的意思是看:
console.log(response['text']) & console.log(food)。如果我做.then(response => response['lang'].slice(-2)),那么当前{'text':'a', 'lang':'bbb'}的响应不会变成'b'吗? @FelixKling -
当然。但是,如果您不希望这样,那么问题不在于参数名称,而在于函数的作用。所有
.thens 都是链式。下一个.then回调接收前一个回调返回的任何内容。彼此无关的参数名称(即.then(response => console.log(response['text']) & console.log(food))中的response与.then(response => response.json())无关。同样,参数的范围是函数。这是您问题的简化示例:function foo(bar) { }; foo(42); console.log(bar);.. .
标签: javascript