在 JavaScript 中将参数转换为数组

什么是 JavaScript 中的 arguments 对象

arguments 是一个存在于每个函数中的对象。无论你在 JavaScript 中传递给函数的什么参数,这些参数都以对象的形式存储在此参数列表中。这个对象的键是从零开始的数字。要访问 arguments 对象中存在的值,我们可以使用这些键。

这个 arguments 对象可以用作数组,但它不支持 JavaScript 函数,如 forEachsortfiltermap。因此,如果你想将这些函数与参数对象一起使用,你必须将整个对象转换为一个数组。

arguments 对象可以通过多种不同的方式转换为数组。我们将关注最流行的方法,例如使用 rest 参数、array.from()array literals。让我们详细讨论它们中的每一个。

在 JavaScript 中使用 rest 参数将 arguments 对象转换为数组

rest 参数允许函数接受可变数量的参数作为输入。它由 ...args 表示。在这里,代替 args,你可以给出任何名称,三个点 ... 被称为扩展运算符。

现在,每当你将 ...args 作为参数传递给函数时,这会将参数对象转换为数组,你现在可以使用名称 args 访问参数对象。

function func(...args) {
    console.log(args);
    console.log(args[0]);
}
func(1,2,3);

输出:

[ 1, 2, 3 ]
1

在这个例子中,我们将参数 1,2,3 作为参数传递给函数 func()。由于我们使用了 rest 运算符,我们将以数组的形式获得 arguments 对象。我们现在可以在这个数组上使用各种方法,比如排序或过滤。

在 JavaScript 中使用 Array.from() 方法将 arguments 对象转换为数组

另一种将参数对象转换为数组的方法是使用方法 Array.from()。在这里,我们必须在 from() 方法中传递参数对象,从而为我们提供一个数组。你可以将结果数组存储到变量中,甚至可以直接访问该数组中的元素。

function func() {
    console.log(Array.from(arguments));
    console.log(Array.from(arguments)[0]);
}
func(1,2,3);

输出:

[ 1, 2, 3 ]
1

我们也采用了相同的示例,但唯一的区别是我们使用 Array.from() 并传入 arguments 对象而不是使用 rest 运算符。你可以使用诸如 Array.from(arguments)[0] 之类的数组索引来访问各个元素。这将返回数组的第一个元素。

在 JavaScript 中使用数组文字arguments 对象转换为数组

array literals 是一个由零个或多个以索引号零开头的元素组成的列表。在 array literals 中,元素包含在方括号 [] 内。在这里,每个元素都可以借助其索引号来访问。

function func() {
    let args = [].slice.call(arguments);
    console.log(args);
    console.log(args[2]);
}
func(1,2,3);

输出:

[ 1, 2, 3 ]
3

要将参数对象转换为数组,我们首先采用了一个空数组。在该数组上,我们使用 call() 方法调用 slice() 方法。现在 slice() 方法将遍历传递的对象。在这种情况下,它是 arguments 对象,然后它将对象内的所有元素附加到空数组中。最后,我们将把 this 的结果存储在一个变量 args 中。

由于此变量现在包含 arguments 对象曾经包含的所有元素,因此你可以使用 args 变量访问每个元素及其适当的索引号。

在 JavaScript 中检测手指滑动事件

本教程教你如何在 JavaScript 中检测手指滑动事件。我们将在使用和不使用 android studio 的情况下完成这项任务。

使用 Android Studio 检测 JavaScript 中的滑动事件

下面给出了先决条件,以遵循这个特定的示例。

  1. Java(从这里下载)。
  2. Android Studio 和 SDK 工具(从这里下载)。

在 Android Studio 中,我们将在 app 文件夹中创建一个新的 assets 文件夹。此外,我们在 assets 文件夹中创建 www 目录,该目录包含 index.html 和 app.js 文件。

WebView 用于加载此 index.html 文件。下面给出了项目树以及创建和修改的文件。

在 JavaScript 中检测手指滑动事件

示例代码(index.html):

<!DOCTYPE html>
<html>
    <head>
        <script src="file:///android_asset/www/app.js"></script>
    <head>
    <body ontouchstart="touchStart(event)" ontouchmove="touchMove(event)"
        ontouchend="touchEnd()">
        <h1>WEBAPP</h1>
    </body>
</html>

示例代码(app.js):

var startX, startY, moveX, moveY;
//here clientX, and clientY means X and Y coordinates
function touchStart(e){
    startX = e.touches[0].clientX ;
    startY = e.touches[0].clientY ;
}

function touchMove(e){
    moveX = e.touches[0].clientX ;
    moveY = e.touches[0].clientY ;
}
function touchEnd(){
    if(startX+100 < moveX){
        console.log('right');
    }else if(startX-100 > moveX){
        console.log('left');
    }
    if(startY+100 < moveY){
        console.log('down');
    }else if(startY-100 > moveY){
        console.log('up');
    }
}

示例代码(MainActivity.java):

package com.example.swipeapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {
    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView browser = findViewById(R.id.webview);
        browser.getSettings().setJavaScriptEnabled(true);
        browser.setWebChromeClient(new WebChromeClient());
        browser.loadUrl("file:///android_asset/www/index.html");
    }
}

示例代码(activity_main.xml):

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity">

 <WebView
 android:id="@+id/webview"
 android:layout_width="match_parent"
 android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

输出:

在 JavaScript 中检测手指滑动事件

在此示例中,我们使用触摸事件来获取滑动结果。如果我们向下滑动,它会显示一条消息 down 让我们知道。

ontouchstart 事件在用户触摸元素时触发,touchend 事件在用户将手指从元素上移开时触发。如果用户开始在屏幕上移动他/她的手指,就会发生 touchMove 事件。

在 JavaScript 中使用 jquery.mobile 检测滑动事件

jquery.mobile 是一个基于 HTML5 的 UI(用户界面),用于开发响应式 Web 应用程序。

HTML 代码:

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-
                1.4.5.min.css">
        <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
        <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js">
        </script>
    </head>
    <body>
        <div data-role="page" id="page_one">
            <div data-role="header">
                <h1>The Swipe Event</h1>
            </div>
            <div data-role="main" class="ui-content">
                <p style="border:1px solid black;margin:5px; padding: 20px;">
                    Swipe me within the border!
                </p>
            </div>
            <div data-role="footer">
                <h1>Footer Text</h1>
            </div>
        </div>
    </body>
</html>

JavaScript 代码:

$(document).on("pagecreate","#page_one",function(){
    $("p").on("swipeleft",function(){
        alert("You swiped left!");
    });
    $("p").on("swiperight",function(){
        alert("You swiped right!");
    });
});

输出:

在 JavaScript 中检测手指滑动事件

如你所见,如果用户在段落内但在边界内向左或向右滑动,我们会检测到 swiperight 和 swipeleft 事件。

在 JavaScript 中使用 swipe-listener 检测滑动事件

swipe-listener 库让网络应用程序监听滑动手势。每当调用 DOM 元素时,该库纯粹检测 swipe 事件并通过 directions 对象检查方向。

HTML 代码:

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-            1.4.5.min.css">
        <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
        <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js">
        </script>
        <script src="https://unpkg.com/swipe-listener@1.2.0/dist/swipe-listener.min.js"             type="text/javascript"></script>
    </head>
    <body>
        <div data-role="page" id="page_one">
            <div data-role="header">
                <h1>The Swipe Event</h1>
            </div>
            <div data-role="main" class="ui-content">
               <p style="border:1px solid black;margin:5px; padding: 20px;">
                    Swipe me within the border!
                </p>
            </div>
            <div data-role="footer">
                <h1>Footer Text</h1>
            </div>
        </div>
    </body>
</html>

JavaScript 代码:

var container = document.querySelector('p');
var listener = SwipeListener(container);
container.addEventListener('swipe', function (e){
    console.log(e.detail);
});

输出:

在 JavaScript 中检测手指滑动事件

在这个输出中,我们得到了许多有用的属性,例如,directions 对象,它告诉你在哪个方向上滑动。