JavaScript数组分配索引值不起作用

发布于 2025-02-11 18:29:06 字数 1899 浏览 3 评论 0原文

我面临这个问题, ”在此处输入图像描述” 控制台输出包含3个数组,第一个在顶部(包含ID),第二个是基于该ID的电影名称,第三个包含电影海报,因此,主要的是在第一个字符串之前的标签[11],尽管其中有11个11个项目,但其他两个阵列没有[11]。因此,因此,我无法获取第一个索引IE标题[0]给出错误,而第一个数组IDS [0]给出了第一个元素。我如何克服这个问题,

我也标记了输出感谢 不知道该如何处理。

<!DOCTYPE html>
    <html>
    <body>
    
        <div id="pred">
    
    
        </div>
    
    
        <script>
            let ids = "[19995, 440, 679, 17663, 602, 7450, 44943, 34851, 11551, 76757, 11260]"
            
            let data = JSON.parse(ids.replaceAll("\""))
            console.log(data)
            let titles = []
            let posters = []
            
            my_api_key = '34b55fa7f2d2346aa1045ed4cc22bd12'
            url1 = 'https://api.themoviedb.org/3/movie/'
            url2 = "https://image.tmdb.org/t/p/w500/" 
            for(i = 0 ; i < data.length ; i++){
             url = url1 + data[i] + '?api_key=' + my_api_key;
            
            fetch(url).then((data)=>{
                return data.json();
            
            }).then((completedata)=>{
                titles.push(completedata.title);
                posters.push(url2 + (completedata.poster_path));
            
            }).catch((err)=>{
                console.log(err)
            })
            
            }
            let my_M = "";
            my_M = `
            <h1 style="color:blue ;">
                    <span>${titles[0]}</span>
            </h1>
            `;
            document.getElementById("pred").innerHTML = my_M;
            
            console.log(titles)
            console.log(posters)
            </script>
    
    
    
    </body>
    
    </html>

I am facing this issue, enter image description hereconsole output contains 3 arrays, the first is on top (contains ids), the second is which contains the movies name based on that id, the third contains the movie poster, so the main thing is tag [11] before the first string that the other two arrays don't have [11], although there are 11 11 items in them. SO due to this, I am unable to fetch the first index i.e. titles[0] give an error while first array ids[0] give the first element. How I can overcome this issue

I also marked the output thanks
Do not know how to deal with this.

<!DOCTYPE html>
    <html>
    <body>
    
        <div id="pred">
    
    
        </div>
    
    
        <script>
            let ids = "[19995, 440, 679, 17663, 602, 7450, 44943, 34851, 11551, 76757, 11260]"
            
            let data = JSON.parse(ids.replaceAll("\""))
            console.log(data)
            let titles = []
            let posters = []
            
            my_api_key = '34b55fa7f2d2346aa1045ed4cc22bd12'
            url1 = 'https://api.themoviedb.org/3/movie/'
            url2 = "https://image.tmdb.org/t/p/w500/" 
            for(i = 0 ; i < data.length ; i++){
             url = url1 + data[i] + '?api_key=' + my_api_key;
            
            fetch(url).then((data)=>{
                return data.json();
            
            }).then((completedata)=>{
                titles.push(completedata.title);
                posters.push(url2 + (completedata.poster_path));
            
            }).catch((err)=>{
                console.log(err)
            })
            
            }
            let my_M = "";
            my_M = `
            <h1 style="color:blue ;">
                    <span>${titles[0]}</span>
            </h1>
            `;
            document.getElementById("pred").innerHTML = my_M;
            
            console.log(titles)
            console.log(posters)
            </script>
    
    
    
    </body>
    
    </html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱的故事 2025-02-18 18:29:06

您要获得{}作为最后两个console.log()的返回的原因是因为当您代码到达时,您的API fetch尚未完成console.log(标题)
Console.log(海报)最后。因此(当时内部)尚不可用的数据。这称为同步运行代码。

为了确保后者的代码将“等待”以前我们需要使代码异步制作代码,您可以在此文章

我不确定您要实现的目标,但是如果您会在下面获得JavaScript代码之类的东西。

编辑:我添加了.then(()=&gt; {})以确保创建元素后呈现的列表。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

</head>
<body>
<div id="pred">


</div>
</body>
</html>
<script>
    const ids = [19995, 440, 679, 17663, 602, 7450, 44943, 34851, 11551, 76757, 11260]
    console.log(ids)
    let titles = []
    let posters = []
    my_api_key = '34b55fa7f2d2346aa1045ed4cc22bd12'
    url1 = 'https://api.themoviedb.org/3/movie/'
    url2 = "https://image.tmdb.org/t/p/w500/"
    const fetchData = url =>
        new Promise(resolve => {
                fetch(url).then((data) => {
                    return data.json();
                }).then((completedata) => {
                    titles.push(completedata.title);
                    posters.push(url2 + (completedata.poster_path));
                    resolve(url)
                }).catch((err) => {
                    console.log(err)
                })
            }
        );

    const fetchAllData = async () => {
        for (let i = 0; i < ids.length; i++) {
            let url = url1 + ids[i] + '?api_key=' + my_api_key;
            await fetchData(url);
        }
        console.log('All data is fetched');
    };
    fetchAllData().then(() => {
        let my_M = "";
        my_M = `
            <h1 style="color:blue ;">
                    <span>${titles[0]}</span>
            </h1>
            `;
        document.getElementById("pred").innerHTML = my_M;
        console.log(titles[0], posters)
    });


</script>

The reason why you are getting the {} as return for the last two console.log() is because your API fetch is not finished when you code reaches the console.log(titles)
and console.log(posters) in the end. So the data which is coming after the fetch (inside then) is not yet available. This is called synchronously running code.

To make sure that the latter piece of code will 'wait' for the earlier piece we need to make the code asynchronously, you can read more about it in this article.

I am not quit sure what you are trying to achieve but if you you would get something like below for your javascript code.

EDIT: I added the .then(()=>{}) to make sure the list on rendered after the element is created.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

</head>
<body>
<div id="pred">


</div>
</body>
</html>
<script>
    const ids = [19995, 440, 679, 17663, 602, 7450, 44943, 34851, 11551, 76757, 11260]
    console.log(ids)
    let titles = []
    let posters = []
    my_api_key = '34b55fa7f2d2346aa1045ed4cc22bd12'
    url1 = 'https://api.themoviedb.org/3/movie/'
    url2 = "https://image.tmdb.org/t/p/w500/"
    const fetchData = url =>
        new Promise(resolve => {
                fetch(url).then((data) => {
                    return data.json();
                }).then((completedata) => {
                    titles.push(completedata.title);
                    posters.push(url2 + (completedata.poster_path));
                    resolve(url)
                }).catch((err) => {
                    console.log(err)
                })
            }
        );

    const fetchAllData = async () => {
        for (let i = 0; i < ids.length; i++) {
            let url = url1 + ids[i] + '?api_key=' + my_api_key;
            await fetchData(url);
        }
        console.log('All data is fetched');
    };
    fetchAllData().then(() => {
        let my_M = "";
        my_M = `
            <h1 style="color:blue ;">
                    <span>${titles[0]}</span>
            </h1>
            `;
        document.getElementById("pred").innerHTML = my_M;
        console.log(titles[0], posters)
    });


</script>

enter image description here

盛夏已如深秋| 2025-02-18 18:29:06

问题是您正在尝试在收到API响应之前访问标题。在JavaScript中,我们称其为异步代码。您可以通过等待其执行完成来使代码同步。您可以使用异步/等待语法来处理此问题。

您可以尝试运行以下代码段。您将在控制台日志上看到一些延迟。

您的获取请求API调用已期待等待。为了使您在功能中使用等待,您需要在函数上添加async关键字。

<!DOCTYPE html>
    <html>
    <body>
    
        <div id="pred">
    
    
        </div>
    
    
        <script>
        async function fetchMoviesJSON(url) {
            const response = await fetch(url);
            const movies = await response.json();
            return movies;
        }
        
        async function fetchTitles() {
            let ids = "[19995, 440, 679, 17663, 602, 7450, 44943,                             34851, 11551, 76757, 11260]";
            
            let data = JSON.parse(ids.replaceAll("\""));

            let titles = [];
            let posters = [];
            
            const my_api_key = '34b55fa7f2d2346aa1045ed4cc22bd12';
            const url1 = 'https://api.themoviedb.org/3/movie/';
            const url2 = "https://image.tmdb.org/t/p/w500/" ;
            for (i = 0 ; i < data.length ; i++) {
                url = url1 + data[i] + '?api_key=' + my_api_key;
                try {
                  const movieResponse = await fetchMoviesJSON(url);
                  titles.push(movieResponse.title);
                  posters.push(url2 + (movieResponse.poster_path));
                } catch (err) {
                  console.log(err);
                }
                const my_M = `
                <h1 style="color:blue ;">
                        <span>${titles[0]}</span>
                </h1>
                `;
                document.getElementById("pred").innerHTML = my_M;
            }
            console.log(titles);
            console.log(posters)
        }
        fetchTitles()
      </script>
    
    
    
    </body>
    
    </html>

The issue is you are trying to access the titles before receiving the response from the API. In javascript we call it asynchronous code. You can make your code synchronous by waiting for its execution to finish. You can use async/await syntax to deal with this.

You can try running the below code snippet. You will see some delay on the console log.

Your fetch request API call is awaited using await. In order for you to use await inside a function, you need to add async keyword on the function.

<!DOCTYPE html>
    <html>
    <body>
    
        <div id="pred">
    
    
        </div>
    
    
        <script>
        async function fetchMoviesJSON(url) {
            const response = await fetch(url);
            const movies = await response.json();
            return movies;
        }
        
        async function fetchTitles() {
            let ids = "[19995, 440, 679, 17663, 602, 7450, 44943,                             34851, 11551, 76757, 11260]";
            
            let data = JSON.parse(ids.replaceAll("\""));

            let titles = [];
            let posters = [];
            
            const my_api_key = '34b55fa7f2d2346aa1045ed4cc22bd12';
            const url1 = 'https://api.themoviedb.org/3/movie/';
            const url2 = "https://image.tmdb.org/t/p/w500/" ;
            for (i = 0 ; i < data.length ; i++) {
                url = url1 + data[i] + '?api_key=' + my_api_key;
                try {
                  const movieResponse = await fetchMoviesJSON(url);
                  titles.push(movieResponse.title);
                  posters.push(url2 + (movieResponse.poster_path));
                } catch (err) {
                  console.log(err);
                }
                const my_M = `
                <h1 style="color:blue ;">
                        <span>${titles[0]}</span>
                </h1>
                `;
                document.getElementById("pred").innerHTML = my_M;
            }
            console.log(titles);
            console.log(posters)
        }
        fetchTitles()
      </script>
    
    
    
    </body>
    
    </html>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文