如何在javascript中為函式的回傳值設定多個變數?此方法不起作用,名稱未定義。
function data() {
var names = ["logan", "harry", "josh", "harris", "jacob"]
var nameFind = "harris"
return names, nameFind
}
names, nameFind = data()
uj5u.com熱心網友回復:
在 JavaScript 中,函式只能回傳一個值。最接近此的是回傳陣列中的值:
return [names, nameFind]
...然后在呼叫代碼中決議陣列
var result = data()
var names = result[0], nameFind = result[1]
此外,根據您作業的環境,最現代的 JS 版本支持行內解構回傳值,如下所示:
[names, nameFind] = data()
uj5u.com熱心網友回復:
JavaScript 不做tuples。而是回傳一個陣列或物件。
您可以使用解構來簡化回傳值的分配
// array
function data() {
const names = ["logan", "harry", "josh", "harris", "jacob"]
const nameFind = "harris"
return [ names, nameFind ]
}
const array = data()
const names = array[0]
const nameFind = array[1]
// or with destructuring
const [ names, nameFind ] = data()
// object
function data() {
const names = ["logan", "harry", "josh", "harris", "jacob"]
const nameFind = "harris"
return {
names: names,
nameFind: nameFind
}
// or with shorthand property names
return { names, nameFind }
}
const obj = data()
const name = obj.name
const nameFind = obj.nameFind
// or with destructuring
const { names, nameFind } = data()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/390117.html
標籤:javascript 功能 返回
