js奇怪的行为数组解构

时间:2018-05-23 06:15:49

标签: javascript destructuring



const test = () => {
  const arr = [1, 2]
  console.log("any strings") // focus on this line
  [arr[0], arr[1]] = [arr[1], arr[0]]
}

const test1 = () => {
  const arr = [1, 2]
  console.log("any strings"); // add a semicolon will works or comment this line will works too
  [arr[0], arr[1]] = [arr[1], arr[0]]
}

test() // error

test1() // works




为什么第一个函数测试抛出错误"无法设置属性' 2'未定义"?

1 个答案:

答案 0 :(得分:2)

这里的问题与解构没有任何关系。在第一个代码段中,因为console.log("any strings")[arr[0], arr[1]] 之后的第二行以开括号开头,所以它将这些行视为同一语句的一部分。

[arr[0], arr[1]]

请注意,在括号表示法中,[arr[1]]将解析为[arr[1]] - 这是逗号运算符。因此,它尝试分配调用[2]结果的console.log("any strings") = const test = () => { const arr = [1,2] console.log("any strings")[arr[0], arr[1]] = [arr[1], arr[0]] } test()属性。对于口译员来说,它与此片段完全相同:



const test = () => {
    const arr = [1,2]
    console.log("any strings")[arr[1]]
      = [arr[1], arr[0]]    
} 

test()




同样:



console.log




当然,undefined会返回foreach ($allorders as $orders){ $orderiddetail = $orders->amazonorderid; // SET Paramater for API request require("amazonListOrderItems.php"); $quantityordered = (int)$orders['ListOrderItemsResult']['OrderItems']['OrderItem']['QuantityOrdered']; $quanityshipped = (int)$orders['ListOrderItemsResult']['OrderItems']['OrderItem']['QuantityShipped']; $title = $orders['ListOrderItemsResult']['OrderItems']['OrderItem']['Title']; if($title === NULL){ $title = ""; } $sellersku = $orders['ListOrderItemsResult']['OrderItems']['OrderItem']['SellerSKU']; if($sellersku === NULL){ $sellersku = ""; } $asins = $orders['ListOrderItemsResult']['OrderItems']['OrderItem']['ASIN']; if($asins === NULL){ $asins = ""; } // INSERT try { $statement = $pdo->prepare("INSERT INTO order_details(amazonorderid, asins, sellersku, title, quantityordered, quantityshipped) VALUES (:orderiddetail, :asins, :sellersku, :title, :quantityordered, :quanityshipped)"); $statement->bindValue(':orderiddetail', $orderiddetail, PDO::PARAM_STR); $statement->bindValue(':asins', $asins, PDO::PARAM_STR); $statement->bindValue(':sellersku', $sellersku, PDO::PARAM_STR); $statement->bindValue(':title', $title, PDO::PARAM_STR); $statement->bindValue(':quantityordered', $quantityordered, PDO::PARAM_INT); $statement->bindValue(':quanityshipped', $quanityshipped, PDO::PARAM_INT); $statement->execute(); } catch (PDOException $e) { if ($e->errorInfo[1] == 1062) { $result = "Double entry"; } else { echo $e; break; } } // INSERT END }; // END of foreach ;它没有这样的财产[2]。如有疑问,请务必使用分号。