如何将您在函数中调用的内容更改为数组
How To Change What You've Called In A Function To An Array
假设我创建了一个翻转数组元素的函数。例如,该函数接收 [1,2,3,4] 并将其翻转到 [4,3,2,1]。我的函数能够做到这一点。但是,我想做一些似乎不起作用的事情。如果我像这样调用函数:flip("hello")
,我希望它"hello"
更改为这样的数组:[h,e,l,l,o]
,将元素翻转成这样:o,l,l,e,h
然后将元素连接在一起以使其olleh
。这是我到目前为止能够做到的:
function reverse (A) {
if(typeof(A) == 'string') { A.toString().split(" "); }
var i1 = 0;
var i2 = A.length - 1;
function swap(A, i1, i2) {
var temp = A[i1];
A[i1] = A[i2];
A[i2] = temp;
return A;
}
var index1 = 0;
var index2 = A.length - 1;
var temp = A[index1];
for(let i = index1; i < index2; i++) {
swap(A, i, index2); index2--;
}
console.log(A);
}
这根本行不通。我认为这是因为我不是在处理所谓的内容,而是在处理参数本身。我也尝试过:
if(typeof(reverse(A)) == 'string') {A.toString().split(" "); }
但是,这给了我一个结果,说:RangeError: Maximum call stack size exceeded
我已经寻找了一个小时,但没有成功。有什么帮助吗?
替换
A.toString().split(" ");
跟
A = A.split(""); // empty string for splitting, splits every character
因为您需要赋值,而A
已经是字符串,所以您不需要toString()
.
稍后您必须返回连接数组:
return A.join('');
使用的方法:
String.prototype.split()
split()
方法通过将字符串分隔为子字符串,将 String 对象拆分为字符串数组。Array.prototype.join()
join()
方法将数组的所有元素联接到一个字符串中。
完成工作代码,并进行一些小的更改:
function reverse(a) {
function swap(b, i1, i2) {
var temp = b[i1];
b[i1] = b[i2];
b[i2] = temp;
}
var index1 = 0,
index2 = a.length - 1,
isString = typeof a === 'string';
if (isString) {
a = a.split("");
}
for (index1 = 0; index1 < index2; index1++) {
swap(a, index1, index2);
index2--;
}
return isString ? a.join('') : a;
}
document.write('<pre>' + JSON.stringify(reverse([100, 101, 102]), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(reverse('hello'), 0, 4) + '</pre>');
<pre><code>
<script>
function myFunction() {
var str = "hello";
var splitting = str.split("");
var reversed_array=splitting.reverse();
var result=reversed_array.join("");
document.getElementById("demo").innerHTML = result;
}
</script>
</code></pre>
使用的函数拆分 :- 这会将字符串拆分为数组。反向 :- 这将用于反转数组。加入 :- 它将加入反向数组JavaScript 字符串数组函数
相关文章:
- 为什么从数组调用时收到非法调用
- JavaScript:从数组调用函数
- 可以将定义的变量放入数组调用中
- 使用包含参数数组的数组调用函数,而不是仅列出数组
- Javascript:从对象数组调用函数
- 下划线:对引发错误的数组数组调用 _.sample
- Javascript 从数组调用对象方法
- 在 Javascript 中使用 setTimeout 从数组调用函数
- 是什么导致我的绘制数组调用无效操作
- 使用变量数组调用函数
- Javasctipt 从数组调用对象的函数
- AngularJS多维数组调用ng repeat
- 如果使用参数数组调用,则日期会更改结果
- 将对象分配给数组,然后根据位置从数组调用它
- 可观察数组——调用webservice列出所有记录并将其绑定到一个表
- 如何从对象数组调用键数组
- 从数组调用函数
- 我可以/应该通过数组调用firebaseRef.set吗
- 数组调用返回未定义
- 从数组调用 JSON 属性