我们假设我们应该得到一些数据......
var data = [];
//some code omitted that might fill in the data (though might not)
Run Code Online (Sandbox Code Playgroud)
然后我们需要对数据做些什么.我的问题是如何更有效地做到这一点.像这样?:
if (data.length) {
for (var i = 0; i < data.length; i++) {
//iterate over the data and do something to it
}
}
Run Code Online (Sandbox Code Playgroud)
或者就是这样?:
for (var i = 0; i < data.length; i++) {
//iterate over the data and do something to it
}
Run Code Online (Sandbox Code Playgroud)
重点是在迭代之前是否检查长度?
假设我已经通过Ajax下载了一个有效的XML文档(var docum = request.responseXML;).现在我如何找出根元素的名称?
我需要学习如何将关联数组传递给函数,以便我可以在函数中执行以下操作:
function someName($argums) {
if (gettype($argums) != 'array' ||
!array_key_exists('myOneKey', $argums) ||
!array_key_exists('myOtherKey', $argums)) {
return false;
}
/*do other stuff*/
}
Run Code Online (Sandbox Code Playgroud)
(这就是我在PHP中用JavaScript做的方法.)
无法绕过这个......
说,我们像这样爆炸整个事情:
$ extract = explode('tra-la-la',$ big_sourse);
然后我们想要获得索引1的值:
$ finish = $ extract [1];
我的问题是如何一气呵成,这样说.与此类似的东西:
$ finish = explode('tra-la-la',$ big_sourse)[1]; //不起作用
像下面这样的东西会像魅力一样:
$ finish = end(explode('tra-la-la',$ big_sourse));
// 要么
$ finish = array_shift(explode('tra-la-la',$ big_sourse));
但是,如果价值位于中间某个位置怎么办?
如何在JavaScript中创建这样的PHP数组?
$arr = array('oneKey' => array('key1' => 'value1',
'key2' => 'value2'),
'anotherKey' => array('key1' => 'value1',
'key2' => 'value2'));
Run Code Online (Sandbox Code Playgroud)
编辑:伙计们,我忘了提到我需要一个简单的方法来按字典顺序对这些数组('key1'=>'value1','key2'=>'value2')进行排序.
EDIT2:其实我不会"转换"它.这是我解释事情的一种方式.我更像是一个骗子.
我有一个函数,用var关键字声明一个变量.然后它启动一个AJAX请求来设置变量的值,然后从该函数返回该变量.
但是,我的实现失败了,我不知道为什么.
这是代码的简化版本;
function sendRequest(someargums) {
/* some code */
var the_variable;
/* some code */
request.onreadystatechange =
//here's that other function
function() {
if (request.readyState == 4) {
switch (request.status) {
case 200:
//here the variable should be changed
the_variable = request.responseXML;
/* a lot of code */
//somewhere here the function closes
}
return the_variable;
}
var data = sendRequest(someargums); //and trying to read the data I get the undefined value
Run Code Online (Sandbox Code Playgroud) javascript ×5
arrays ×2
ajax ×1
dereference ×1
explode ×1
loops ×1
optimization ×1
php ×1
php-5.3 ×1
xml ×1