PHP`extract`函数是否等同于Nodejs(javascript)?
Php提取函数PHP`extract`函数是否等同于Nodejs(javascript)?,javascript,php,arrays,node.js,Javascript,Php,Arrays,Node.js,Php提取函数 <?php $a = "Original"; $my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse"); extract($my_array); echo $a; // this will print Cat ?> 我试过使用this和eval,但它只在浏览器中工作,在NodeJs中怎么可能呢? 评估 var k = { a: 'a0', b: 'b0' } Object.keys(k
<?php
$a = "Original";
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo $a; // this will print Cat
?>
我试过使用this
和eval
,但它只在浏览器中工作,在NodeJs中怎么可能呢?
评估
var k = { a: 'a0', b: 'b0' }
Object.keys(k).forEach((key) => {
eval(`${key}=k[key]`);
console.log(a)
});
这个
function convertKeyToVariable(data, where) {
for (var key in data) {
where[key] = data[key];
}
}
var k = { a: 'Cat', b: 'Dog' }
convertKeyToVariable(k, this)
console.log(a) // will print Cat
注意:我的对象有这么多键,我不想通过键入每个键名来破坏对象。可以使用“破坏结构”
你可以使用解构
从您的建议开始,简单地说不那么笼统,按照我自己的建议使用
global
或this
因此可以在节点和浏览器中工作
function extract(data, where) {
var g = where || (typeof global !== 'undefined' ? global : this);
for (var key in data){
if (data.hasOwnProperty(key)){
g[key] = data[key];
}
}
}
var k = { a: 'Cat', b: 'Dog' }
extract(k)
console.log(a) // will print Cat
console.log(b)
从您的建议开始,简单地说不那么笼统,按照我自己的建议使用
global
或this
因此可以在节点和浏览器中工作
function extract(data, where) {
var g = where || (typeof global !== 'undefined' ? global : this);
for (var key in data){
if (data.hasOwnProperty(key)){
g[key] = data[key];
}
}
}
var k = { a: 'Cat', b: 'Dog' }
extract(k)
console.log(a) // will print Cat
console.log(b)
这回答了你的问题吗?调用
convertKeyToVariable
@fedeghe时,请尝试使用global
而不是this
。感谢您在使用global
后它工作正常。我错过了这个回答你的问题吗?调用convertKeyToVariable
@fedeghe时,请尝试使用global
而不是this
。感谢您在使用global
后它工作正常。我错过了这个对象有这么多的关键点和关键点可以是动态的。不想使用destructuringobject有这么多键,键可能是动态的。不想使用解构
function extract(data, where) {
var g = where || (typeof global !== 'undefined' ? global : this);
for (var key in data){
if (data.hasOwnProperty(key)){
g[key] = data[key];
}
}
}
var k = { a: 'Cat', b: 'Dog' }
extract(k)
console.log(a) // will print Cat
console.log(b)