Laravel集合到javascript变量

Laravel集合到javascript变量,javascript,php,laravel,Javascript,Php,Laravel,为什么laravel集合可以直接用作javascript变量而不是php数组或对象 在testing.blade.php中 <?php use Illuminate\Support\Collection; $testingArray = [1,2,3]; $testingObject = new stdClass(); $testingObject->testing = "Testing"; $testingObject->hello = "Hel

为什么laravel集合可以直接用作javascript变量而不是php数组或对象

在testing.blade.php中

<?php
use Illuminate\Support\Collection;
$testingArray = [1,2,3];
$testingObject = new stdClass();
$testingObject->testing = "Testing";
$testingObject->hello = "Hello";
$testingObject->bye = "Bye";
$testingCollection = Collection::make($testingArray);
?>

<script>
        var myArray = {!! $testingArray !!}; //Not work 
        var myObject = {!! $testingObject !!}; //Not work 

        var myArray = {!! json_encode($testingArray) !!}; //Work
        var myObject = {!! json_encode($testingObject) !!}; //Work
        var myCollection = {!! $testingCollection !!}; //Work
</script>

var myArray={!!$testingArray!!}//不行
var myObject={!!$testingObject!!}//不行
var myArray={!!json_encode($testingArray)!!}//工作
var myObject={!!json_encode($testingObject)!!}//工作
var myCollection={!!$testingCollection!!}//工作

有任何引用吗?

这是因为当您将对象转换为字符串时,
Collection
对象会自动序列化为JSON

模型和集合在转换为字符串时转换为JSON

您显示的代码如下:

{!! $testingCollection !!}
尝试将
$testingCollection
输出到视图。这样做显然需要将其转换为字符串。根据文档,这将自动触发其JSON序列化

这是通过其标准的
\uu toString()
函数实现的,该函数指向一个trait,该trait调用
toJSON()
来执行序列化


这反过来意味着JavaScript可以立即读取它,因为正如您可能知道的,有效的JSON可以用作JavaScript对象文本(因为JSON语法是JS对象语法的子集)。

输出
{!!!!!!}
之间发生的事情。PHP无法打印数组和对象,因为它没有任何关于如何将它们转换为字符串的说明。Laravel Collection对象可能已经实现了允许转换的
\uuu-toString
,并且指向。不要忘记
@json
指令!